/*
 * @Author: 张仁会 28396543@qq.com
 * @Date: 2022-07-28 18:42:03
 * @LastEditors: 张仁会 28396543@qq.com
 * @LastEditTime: 2022-08-18 15:17:51
 * @FilePath: \exp-jwt\routes\zrh.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%A
 */
var express = require('express');
const log = require('node-dev/lib/log');
var router = express.Router();

// 上传图片
const path = require('path');
const fs = require('fs');
let multer = require('multer');
const { send } = require('process');
//设置上传的的图片保存目录
let objMulter = multer({ dest: './public/images/' });
// 上传任何文件objMulter.any()
router.use(objMulter.any())
router.post('/upload', function (req, res, next) {
    const newname = req.files[0].path + path.parse(req.files[0].originalname).ext
    fs.rename(req.files[0].path, newname, function (err) {
        if (err) {
            res.send({
                msg: '上传失败',
                code: 200,
                data: newname,
            })
        } else {
            res.send({
                msg: '上传成功',
                code: 200,
                data: newname,
            })
        }
    })
})


// 获取登录用户-关注列表
router.post('/getFollowList', async function (req, res, next) {
    let { id } = req.body
    // 只获取普通用户  level=3
    let userAll = await global.query(`select * from meet_userlist where level=3`);
    let followlist = await global.query(`select * from followlist where type=1`);
    let follow_mid = await global.query(`select * from followlist where mid=${id} and  type=1`)
    let follow_yid = await global.query(`select * from followlist where yid=${id} and  type=1`)
    let myFollow = []
    let followMy = []
    let tj = []
    let tjData = []
    userAll.forEach(item => {
        // 筛选我关注的用户
        follow_mid.forEach(ite => {
            if (Number(item.id) === Number(ite.yid)) {
                myFollow.push(item)
            }
        })
        // 筛选关注我的用户
        follow_yid.forEach(ite => {
            if (Number(item.id) === Number(ite.yid)) {
                followMy.push(item)
            }
        })
    })
    //筛选关注了我关注的用户
    followlist.forEach(ite => {
        myFollow.forEach(it => {
            if (Number(ite.mid) !== id && Number(ite.yid) === Number(it.id)) {
                tj.push(ite)
            }
            tj.forEach((i, n) => {
                if (Number(it.id) === Number(i.mid)) {
                    tj.splice(n, 1)
                }
            })
        })
    })
    userAll.forEach(item => {
        tj.forEach(ite => {
            if (Number(item.id) === Number(ite.mid)) {
                tjData.push(item)
            }
        })
    })
    res.send({
        msg: '成功',
        code: 200,
        userAll,//所有用户
        followlist,//关注列表
        myFollow,//我关注的用户
        followMy,//关注我的用户
        tjData,//推荐的用户

    })
});
// 获取登录用户-聊天用户列表
router.post('/getNewsList', async function (req, res, next) {
    let { id } = req.body
    let userAll = await global.query(`select * from meet_userlist where level=3`);
    let news_mid = await global.query(`select * from newslist where mid=${id}`)
    let arr = []
    let newsUser = []
    // 去重函数
    function unique(arr) {
        // 排序
        arr.sort((a, b) => a - b)
        // 去重
        let newArr = arr.reduce((prev, next) => {
            if (prev.indexOf(next) === -1) {
                prev.push(next)
            }
            return prev
        }, [])
        return newArr
    }
    // 筛选聊天的用户信息
    userAll.forEach(item => {
        news_mid.forEach(ite => {
            if (Number(item.id) === Number(ite.yid)) {
                arr.push(item)
            }
        })
    })
    newsUser = unique(arr)
    res.send({
        msg: '成功',
        code: 200,
        newsUser,//聊天的用户信息
    })
});
// 获取登录用户-聊天内容
router.post('/getNewsData', async function (req, res, next) {
    let { loginId, userId } = req.body
    let userAll = await global.query(`select * from meet_userlist where level=3`);
    let news_mid = await global.query(`select * from newslist where mid=${loginId}`);
    let news_yid = await global.query(`select * from newslist where yid=${loginId}`);
    let arr = []
    let newsData = []
    // 去重函数
    function unique(arr) {
        // 排序
        arr.sort((a, b) => a - b)
        // 去重
        let newArr = arr.reduce((prev, next) => {
            if (prev.indexOf(next) === -1) {
                prev.push(next)
            }
            return prev
        }, [])
        return newArr
    }
    // 筛选聊天的用户信息
    userAll.forEach(item => {
        arr = []
        news_mid.forEach(ite => {
            if (Number(item.id) === Number(ite.yid)) {
                arr.push(item)
            }
        })
    })
    let data_mid = await global.query(`select * from newslist where mid=${loginId} and yid=${userId}`);
    let data_yid = await global.query(`select * from newslist where yid=${loginId} and mid=${userId}`);

    // 合并聊天记录并排序
    let newArr = [...data_mid, ...data_yid].sort((a, b) => {
        return new Date(a.time).getTime() - new Date(b.time).getTime()
    })
    // 截取掉已删除聊天记录
    let index = newArr.length - 1
    while (index > 0) {
        if (newArr[index].type.indexOf(loginId) !== -1) {
            newArr.splice(index, 1)
        }
        index--
    }
    // 将聊天记录左右分开
    let arr1 = []
    newArr.forEach(ite => {
        if (Number(ite.mid) === Number(loginId)) {
            // 登录用户发的消息
            arr1.push({
                type: 'right',
                id: ite.id,
                userid: ite.mid,
                name: '',
                img: '',
                content: ite.content,
                time: ite.time
            })
        } else if (Number(ite.mid) === Number(userId)) {
            // 好友回消息
            arr1.push({
                type: 'left',
                id: ite.id,
                userid: ite.mid,
                name: '',
                img: '',
                content: ite.content,
                time: ite.time
            })
        }
    })
    // 获取到用户头像及姓名
    userAll.forEach(item => {
        arr = []
        arr1.forEach(ite => {
            if (Number(ite.userid) === Number(item.id)) {
                ite.name = item.name
                ite.img = item.img
            }
        })
    })
    res.send({
        msg: '成功',
        code: 200,
        data: arr1
        // newsUser,//聊天的用户信息
        // newsData,//聊天记录
    })
});
// 添加聊天内容
router.post('/addNewsData', async function (req, res, next) {
    let { loginId, userId, inputVal, time } = req.body
    let newslist = await global.query(`select * from newslist`);
    let id = Math.max(newslist[newslist.length - 1].id) + 1
    await global.query(`insert into newslist(id,mid,yid,content,time,type) value(${id},${loginId},${userId},'${inputVal}','${time}',0)`);
    res.send({
        msg: '成功',
        code: 200,
    })
})
// 删除聊天内容
router.post('/delNewsData', async function (req, res, next) {
    let { loginId, itemId } = req.body
    await global.query(`update newslist set type='${loginId}' where id=${itemId}`);
    res.send({
        msg: '成功',
        code: 200,
    })
})
// 修改消息数量
router.post('/setNewsNum', async function (req, res, next) {
    let { id, num } = req.body
    console.log(id, num);
    await global.query(`update meet_userlist set num='${num}' where id=${id}`)
    res.send({
        msg: '成功',
        code: 200,
    })
})
// 关注
router.post('/setFollow', async function (req, res, next) {
    let { mid, yid, time, type } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let followlist = await global.query(`select * from followlist`);
    let systemnews = await global.query(`select * from systemnews`);
    let followlistID = Math.max(followlist[followlist.length - 1].id) + 1
    let systemnewsID = Math.max(systemnews[systemnews.length - 1].id) + 1
    let result = followlist.find(item => {
        if (Number(item.mid) === Number(mid) && Number(item.yid) === Number(yid)) {
            return item
        }
    })
    if (type === 0) {
        // 取消关注--直接修改数据
        await global.query(`update followlist set time='${time}',type='${type}' where mid=${mid} and yid=${yid}`);
    } else if (type === 1) {
        // 关注
        if (result) {
            // 数据存在---修改
            await global.query(`update followlist set time='${time}',type='${type}' where mid=${mid} and yid=${yid}`);
        } else {
            // 数据不存在----添加
            await global.query(`insert into followlist(id,mid,yid,time,type) value(${followlistID},${mid},${yid},'${time}',${type})`);
        }
    }
    // 获取发起关注的name
    let name = ''
    userAll.forEach(item => {
        if (Number(item.id) === Number(mid)) {
            name = item.name
        }
    })
    // 向系统消息中添加一条关注的数据
    await global.query(`insert into systemnews(id,mid,yid,uid,title,content,time,type) value(${systemnewsID},11,${yid},${mid},'关注了你','${name}+关注了你','${time}',0)`);
    res.send({
        msg: '成功',
        code: 200,
    })
})
// 获取--关注+粉丝数量
router.post('/getFsGzNum', async function (req, res, next) {
    let { id } = req.body
    let follow_mid = await global.query(`select * from followlist where mid=${id} and  type=1`)
    let follow_yid = await global.query(`select * from followlist where yid=${id} and  type=1`)
    res.send({
        msg: '成功',
        code: 200,
        followNum: follow_mid.length,
        fansNum: follow_yid.length
    })
})




// 获取登录用户---系统聊天用户列表
router.post('/getSystemNews', async function (req, res, next) {
    let { id, } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let news_yid = await global.query(`select * from systemnews where yid=${id}`)
    let arr = []
    let newsUser = []
    // 筛选聊天的--用户信息
    userAll.forEach(item => {
        news_yid.forEach(ite => {
            if (Number(item.id) === Number(ite.mid)) {
                arr.push(item)
            }
        })
    })
    // 去重函数
    function unique(arr) {
        // 排序
        arr.sort((a, b) => a - b)
        // 去重
        let newArr = arr.reduce((prev, next) => {
            if (prev.indexOf(next) === -1) {
                prev.push(next)
            }
            return prev
        }, [])
        return newArr
    }
    newsUser = unique(arr)
    // 根据发消息的时间筛选最后一条
    function searchLast(arr) {
        let obj = arr.reduce((prev, next) => {
            if (new Date(prev.time).getTime() > new Date(next.time).getTime()) {
                return prev
            } else {
                return next
            }
        }, { time: '2000-07-01 11:30:55' })
        return obj
    }
    // 给每个用户添加一个news变量将最后一条消息加上
    newsUser.forEach(item => {
        let arr = []
        news_yid.forEach(ite => {
            if (item.id === ite.mid) {
                arr.push(ite)
            }
        })
        let obj = searchLast(arr)
        let newObj = {}
        userAll.forEach(ite => {
            if (ite.id === obj.uid) {
                newObj.name = ite.name
                newObj.uid = obj.uid
                newObj.title = obj.title
            } else {
                newObj.uid = obj.uid
                newObj.title = obj.title
            }
        })
        item.news = newObj
    })
    res.send({
        msg: '成功',
        code: 200,
        newsUser,//聊天的用户信息
    })
});
// 获取登录用户---系统聊天内容
router.post('/getSystemNewsData', async function (req, res, next) {
    let { loginId, userId } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let systemnews = await global.query(`select * from systemnews where yid=${loginId}`);
    let arr = []
    let newsData = []
    // 去重函数
    function unique(arr) {
        // 排序
        arr.sort((a, b) => a - b)
        // 去重
        let newArr = arr.reduce((prev, next) => {
            if (prev.indexOf(next) === -1) {
                prev.push(next)
            }
            return prev
        }, [])
        return newArr
    }
    // 筛选聊天的用户信息
    systemnews.forEach(item => {
        if (Number(userId) === (11 && Number(item.mid))) {
            // 系统消息
            let obj = {}
            userAll.forEach((ite) => {
                if (Number(item.uid) === Number(ite.id)) {
                    obj = ite
                }
            })
            item.mUser = obj
            arr.push(item)
        } else if (Number(userId) === ((12 || 13) && Number(item.mid))) {
            // 系统通知+活动
            arr.push(item)
        }
    })
    res.send({
        msg: '成功',
        code: 200,
        data: arr
    })
});
// 添加---系统聊天内容
// router.post('/addSystemNews', async function (req, res, next) {
// let { loginId, userId, inputVal, time } = req.body
// let data = await global.query(`select * from newslist`);
// let id = Math.max(data[data.length - 1].id) + 1
// await global.query(`insert into newslist(id,mid,yid,content,time,type) value(${id},${loginId},${userId},'${inputVal}','${time}','')`);
// res.send({
//     msg: '成功',
//     code: 200,
// })
// })
// 删除---系统聊天内容
router.post('/delSystemNews', async function (req, res, next) {
    let { loginId, itemId } = req.body
    await global.query(`update systemnews set type='${loginId}' where id=${itemId}`);
    res.send({
        msg: '成功',
        code: 200,
    })
})




// pc添加系统消息
router.post('/addSystemNews', async function (req, res, next) {
    let { mid, yid, uid, title, content, startTime, endTime, time } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let m, y
    userAll.forEach(item => {
        if (item.name === mid) {
            m = item.id
        }
        if (item.name === yid) {
            y = item.id
        }
    })
    let systemnews = await global.query(`select * from systemnews`);
    let id = Math.max(systemnews[systemnews.length - 1].id) + 1
    await global.query(`insert into systemnews(id,mid,yid,uid,title,content,startTime,endTime,time,type) value(${id},${m},${y},${uid},'${title}','${content}','${startTime}','${endTime}','${time}',0)`);
    res.send({
        msg: '成功',
        code: 200,
    })
})
// pc添加用户消息
router.post('/addUserNews', async function (req, res, next) {
    let { loginId, userId, inputVal, time } = req.body
    let newslist = await global.query(`select * from newslist`);
    let id = Math.max(newslist[newslist.length - 1].id) + 1
    await global.query(`insert into newslist(id,mid,yid,content,time,type) value(${id},${loginId},${userId},'${inputVal}','${time}',0)`);
    res.send({
        msg: '成功',
        code: 200,
    })
})
// pc删除系统消息
router.post('/delSystemNews', async function (req, res, next) {
    let { data } = req.body
    data.forEach(ite => {
        // global.query(`delete from systemnews where id=${ite}`);
    })
    res.send({
        msg: '成功',
        code: 200,
    })
})
// pc删除用户消息
router.post('/delUserNews', async function (req, res, next) {
    let { data } = req.body
    console.log(delArr);
    data.forEach(ite => {
        // global.query(`delete from newslist where id=${ite}`);
    })
    res.send({
        msg: '成功',
        code: 200,
    })
})
// pc修改系统消息
router.post('/setSystemNews', async function (req, res, next) {
    let { id, mid, yid, uid, title, content, startTime, endTime, time } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let y
    userAll.forEach(item => {
        if (item.name === yid) {
            y = item.id
        }
    })
    await global.query(`update systemnews set yid=${y}, title='${title}', content='${content}', startTime='${startTime}', endTime='${endTime}', time='${time}' where id=${id}`)

    res.send({
        msg: '成功',
        code: 200,
    })
})
// pc修改用户消息
router.post('/setUserNews', async function (req, res, next) {
    let { id } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let newslist = await global.query(`select * from newslist`);
    let systemlist = await global.query(`select * from systemnews`);
    userAll.forEach((item) => {
        newslist.forEach((ite => {
            if (Number(item.id) === Number(ite.mid)) {
                ite.mid = item.name
            }
            if (Number(item.id) === Number(ite.yid)) {
                ite.yid = item.name
            }
        }))
        systemlist.forEach((ite => {
            if (Number(item.id) === Number(ite.mid)) {
                ite.mid = item.name
            }
            if (Number(item.id) === Number(ite.yid)) {
                ite.yid = item.name
            }
            if (Number(item.id) === Number(ite.uid)) {
                ite.uid = item.name
            }
        }))
    })

    res.send({
        msg: '成功',
        code: 200,
        newslist,
        systemlist,
    })
})
// pc获取消息列表
router.post('/getData', async function (req, res, next) {
    let { id } = req.body
    let userAll = await global.query(`select * from meet_userlist`);
    let newslist = await global.query(`select * from newslist`);
    let systemlist = await global.query(`select * from systemnews`);
    userAll.forEach((item) => {
        newslist.forEach((ite => {
            if (Number(item.id) === Number(ite.mid)) {
                ite.mid = item.name
            }
            if (Number(item.id) === Number(ite.yid)) {
                ite.yid = item.name
            }
        }))
        systemlist.forEach((ite => {
            if (Number(item.id) === Number(ite.mid)) {
                ite.mid = item.name
            }
            if (Number(item.id) === Number(ite.yid)) {
                ite.yid = item.name
            }
            if (Number(item.id) === Number(ite.uid)) {
                ite.uid = item.name
            }
        }))
    })

    res.send({
        msg: '成功',
        code: 200,
        userAll,
        newslist,
        systemlist,
    })
})

module.exports = router